<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8" />
    <title>剪贴板历史</title>
    <style>
        body {
            margin: 0;
            font-family: system-ui, sans-serif;
            background: #f7f7f7;
        }

        .container {
            padding: 18px;
        }

        h2 {
            margin: 0 0 12px 0;
            font-size: 20px;
        }

        .item {
            background: #fff;
            border-radius: 6px;
            margin-bottom: 10px;
            padding: 12px;
            box-shadow: 0 1px 4px #0001;
            cursor: pointer;
            transition: box-shadow .2s;
        }

        .item:hover {
            box-shadow: 0 2px 8px #0002;
            background: #f0f8ff;
        }

        .actions {
            margin-bottom: 12px;
        }

        .actions button {
            margin-right: 8px;
        }

        .empty {
            color: #aaa;
            text-align: center;
            margin-top: 40px;
        }

        #favorites {
            margin-bottom: 18px;
        }

        #context-menu {
            position: fixed;
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-shadow: 0 2px 8px #0002;
            z-index: 9999;
            min-width: 90px;
        }

        #context-menu div {
            padding: 10px 18px;
            cursor: pointer;
        }

        #context-menu div:hover {
            background: #f0f0f0;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2>剪贴板历史</h2>
        <div class="actions">
            <button onclick="clearHistory()">清空历史</button>
            <button onclick="fetchHistory()">刷新</button>
            <button id="toggle-fav" onclick="toggleFavorites()">只看收藏</button>
            <button onclick="window.close()">关闭</button>
        </div>
        <div id="favorites"></div>
        <div id="list"></div>
        <div class="empty" id="empty" style="display:none;">暂无历史记录</div>
    </div>
    <script>
        // 检查 window.api.clipboardHistory 是否注入
        if (!window.api || !window.api.clipboardHistory) {
            document.body.innerHTML = '<div style="color:red;padding:32px;">window.api.clipboardHistory 未注入，请检查 preload 和 webPreferences 设置！</div>';
            throw new Error('window.api.clipboardHistory 未注入');
        }
        let favorites = JSON.parse(localStorage.getItem('clipboardFavorites') || '[]')
        function saveFavorites() {
            localStorage.setItem('clipboardFavorites', JSON.stringify(favorites))
        }
        function renderFavorites() {
            const favDiv = document.getElementById('favorites')
            favDiv.innerHTML = ''
            if (onlyShowFavorites) {
                favDiv.style.display = 'none'
                return
            }
            favDiv.style.display = ''
            if (!favorites.length) return
            favDiv.innerHTML = '<h4 style="margin:0 0 8px 0;color:#f90;font-size:15px;">★ 收藏</h4>'
            favorites.forEach((item, idx) => {
                const div = document.createElement('div')
                div.className = 'item'
                div.textContent = item.length > 200 ? item.slice(0, 200) + '...' : item
                div.title = item
                div.style.background = '#fffbe6'
                div.onclick = async () => {
                    await window.api.clipboardHistory.copy(item)
                    showToast('已复制到剪贴板')
                }
                div.oncontextmenu = (e) => {
                    e.preventDefault()
                    showFavMenu(e.clientX, e.clientY, item)
                }
                favDiv.appendChild(div)
            })
        }
        function addFavorite(item) {
            if (!favorites.includes(item)) {
                favorites.unshift(item)
                if (favorites.length > 50) favorites = favorites.slice(0, 50)
                saveFavorites()
                renderFavorites()
                showToast('已收藏')
            }
        }
        function showMenu(x, y, item) {
            let menu = document.getElementById('context-menu')
            if (menu) menu.remove()
            menu = document.createElement('div')
            menu.id = 'context-menu'
            menu.style.left = x + 'px'
            menu.style.top = y + 'px'
            menu.innerHTML = `
                <div id="menu-copy">复制</div>
                <div id="menu-fav">收藏</div>
            `
            document.body.appendChild(menu)
            document.getElementById('menu-copy').onclick = async () => {
                await window.api.clipboardHistory.copy(item)
                showToast('已复制到剪贴板')
                menu.remove()
            }
            document.getElementById('menu-fav').onclick = () => {
                addFavorite(item)
                // 不再调用 window.api.clipboardHistory.copy(item)
                menu.remove()
            }
            document.addEventListener('mousedown', function handler(e) {
                if (!menu.contains(e.target)) menu.remove(), document.removeEventListener('mousedown', handler)
            })
        }
        function showFavMenu(x, y, item) {
            let menu = document.getElementById('context-menu')
            if (menu) menu.remove()
            menu = document.createElement('div')
            menu.id = 'context-menu'
            menu.style.position = 'fixed'
            menu.style.left = x + 'px'
            menu.style.top = y + 'px'
            menu.style.background = '#fff'
            menu.style.border = '1px solid #ddd'
            menu.style.borderRadius = '6px'
            menu.style.boxShadow = '0 2px 8px #0002'
            menu.style.zIndex = 9999
            menu.style.minWidth = '120px'
            menu.innerHTML = `
                <div id="menu-copy">复制</div>
                <div id="menu-unfav">取消收藏</div>
                <div id="menu-view">查看内容</div>
            `
            document.body.appendChild(menu)
            document.getElementById('menu-copy').onclick = async () => {
                await window.api.clipboardHistory.copy(item)
                showToast('已复制到剪贴板')
                menu.remove()
            }
            document.getElementById('menu-unfav').onclick = () => {
                favorites = favorites.filter(f => f !== item)
                saveFavorites()
                renderFavorites()
                showToast('已取消收藏')
                menu.remove()
            }
            document.getElementById('menu-view').onclick = () => {
                showContentDialog(item)
                menu.remove()
            }
            document.addEventListener('mousedown', function handler(e) {
                if (!menu.contains(e.target)) menu.remove(), document.removeEventListener('mousedown', handler)
            })
        }
        // 新增：弹窗显示内容
        function showContentDialog(content) {
            let dialog = document.createElement('div')
            dialog.style.position = 'fixed'
            dialog.style.left = '50%'
            dialog.style.top = '50%'
            dialog.style.transform = 'translate(-50%, -50%)'
            dialog.style.background = '#fff'
            dialog.style.padding = '24px 28px'
            dialog.style.borderRadius = '8px'
            dialog.style.boxShadow = '0 4px 24px #0004'
            dialog.style.zIndex = 10000
            dialog.style.maxWidth = '80vw'
            dialog.style.maxHeight = '60vh'
            dialog.style.overflow = 'auto'
            dialog.innerHTML = `<div style='white-space:pre-wrap;word-break:break-all;font-size:15px;line-height:1.7;'>${content.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</div><div style='text-align:right;margin-top:18px;'><button id='dialog-close'>关闭</button></div>`
            document.body.appendChild(dialog)
            document.getElementById('dialog-close').onclick = () => dialog.remove()
        }
        let onlyShowFavorites = false
        function toggleFavorites() {
            onlyShowFavorites = !onlyShowFavorites
            fetchHistory()
            document.getElementById('toggle-fav').textContent = onlyShowFavorites ? '显示全部' : '只看收藏'
        }
        async function fetchHistory() {
            const history = await window.api.clipboardHistory.get()
            const list = document.getElementById('list')
            const empty = document.getElementById('empty')
            list.innerHTML = ''
            let showList = onlyShowFavorites ? favorites : history
            if (!showList || showList.length === 0) {
                empty.style.display = ''
                return
            }
            empty.style.display = 'none'
            showList.forEach((item, idx) => {
                const div = document.createElement('div')
                div.className = 'item'
                div.textContent = item.length > 200 ? item.slice(0, 200) + '...' : item
                div.title = item
                // 左键点击无操作
                div.onclick = null
                div.oncontextmenu = (e) => {
                    e.preventDefault()
                    showMenu(e.clientX, e.clientY, item)
                }
                list.appendChild(div)
            })
            renderFavorites()
        }
        async function clearHistory() {
            await window.api.clipboardHistory.clear()
            fetchHistory()
        }
        // 自动刷新说明：每次有新复制内容时自动刷新历史列表，无需手动点击刷新按钮
        window.addEventListener('DOMContentLoaded', fetchHistory)
        // 监听主进程推送的剪贴板历史变更事件
        if (window.api && window.api.clipboardHistory) {
            if (window.api.clipboardHistory.onUpdate) {
                window.api.clipboardHistory.onUpdate(fetchHistory)
            } else if (window.electron && window.electron.ipcRenderer) {
                window.electron.ipcRenderer.on('clipboard-history-updated', fetchHistory)
            }
        }

        // 简单右下角弹窗提示
        function showToast(msg) {
            let toast = document.createElement('div')
            toast.textContent = msg
            toast.style.position = 'fixed'
            toast.style.right = '32px'
            toast.style.bottom = '32px'
            toast.style.background = '#222a'
            toast.style.color = '#fff'
            toast.style.padding = '8px 18px'
            toast.style.borderRadius = '6px'
            toast.style.fontSize = '15px'
            toast.style.zIndex = 9999
            toast.style.boxShadow = '0 2px 8px #0003'
            document.body.appendChild(toast)
            setTimeout(() => toast.remove(), 1200)
        }

        // 兼容 window.api.clipboardHistory.copy 方法
        if (window.api && window.api.clipboardHistory && !window.api.clipboardHistory.copy) {
            window.api.clipboardHistory.copy = async (text) => {
                // 直接写入系统剪贴板
                if (window.electron && window.electron.clipboard) {
                    window.electron.clipboard.writeText(text)
                } else if (navigator.clipboard) {
                    await navigator.clipboard.writeText(text)
                }
            }
        }
    </script>
</body>

</html>